<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>商品抠图&海报合成</title>
  <script src="../common/cos-js-sdk-v5.min.js"></script>
  <style>
    html,body {
      margin: 0;
      padding: 0;      
    }
    .container {        
      padding: 20px;
    }
    #err-msg {
      font-size: 12px;
      color: #ff0000;
    }
    .poster-area {
      margin: 20px;
    }
    .img-area {
      width: 700px;      
      height: auto;      
    }
    .img-area img {
      width: 100%;
    }
  </style>
</head>
<body>
  <div class="container">
    <div>      
      <input type="file" id="file-selector"/>
      <span id="err-msg"></span>
    </div>
    <div class="poster-area">
      <p>海报生成结果：</p>
      <ul id="poster-results"></ul>
    </div>
    <div class="img-area">
      <img src="" id="sourceFile"/>
      <img src="" id="targetFile"/>
    </div>
  </div>
  <script src="../common/xml2json.js"></script>
  <script>

    /*
      准备工作：
      1. 在cos控制台创建一个存储桶，可拿到存储桶名称和地域，即Bucket，Region。
      2. 进入存储桶配置页面，设置对应的跨域规则（简单调试可将来源Origin设置为*）。
      3. 进入访问管理控制台，获取API密钥，即SecretId，SecretKey。
    
    /* 商品海报合成步骤：
      1. 获取海报合成模版
      2. 使用视频抠图功能提取商品主体图片
      3. 使用海报合成模版创建海报合成任务
      4. 查询海报合成结果
    */
            
    // 注意：以下初始化方式仅供联调测试使用，为了安全起见，请勿在生产环境直接暴露密钥。
    // 生产环境请参考各语言SDK签名实现。https://cloud.tencent.com/document/product/436/7778#sdk-.E7.AD.BE.E5.90.8D.E5.AE.9E.E7.8E.B0

    // 密钥请在访问管理控制台获取。https://console.cloud.tencent.com/cam/capi
    let cos = new COS({
      SecretId: 'AKID*****************************',
      SecretKey: '********************************'
    });

    // 存储桶配置请在cos控制台获取。https://console.cloud.tencent.com/cos/bucket
    // 格式参考：Bucket: 'abc-1250000000', Region: 'ap-shanghai'
    let bucketConf = {
      Bucket: '***-***********',
      Region: '**-*****'
    };

    // 拉取海报合成模板列表请求及参数格式，可参考文档 https://cloud.tencent.com/document/product/460/82387
    let host = bucketConf.Bucket + '.ci.' + bucketConf.Region + '.myqcloud.com';
    let templateId = '';
    cos.request({
      Method: 'GET',
      Url: 'https://' + host + '/posterproduction/template?pageSize=100&type=All',
      Key: '/posterproduction/template',
    }, (err, data) => {
      // 这里方便体验可以直接取默认首个模板
      templateId = data.Response.TemplateList[0].templateId;
    })

    let fileSelectorEle = document.getElementById('file-selector'),
        errMsgEle = document.getElementById('err-msg'),
        sourceFileEle = document.getElementById('sourceFile'),
        posterResultsEle = document.getElementById('poster-results');

    fileSelectorEle.onchange = function(e) {

      errMsgEle.innerHTML = '';
      sourceFileEle.setAttribute('src', '');
      posterResultsEle.innerHTML = '';

      let file = this.files[0];      

      if (!file) {
        errMsgEle.innerHTML = '未发现上传文件';
        return;
      }        

      if(!['image/jpeg', 'image/png', 'image/bmp', 'application/pdf'].includes(file.type)) {        
        e.target.value = '';
        errMsgEle.innerHTML = '当前仅支持图片格式：PNG、JPG、JPEG、BMP 及 PDF 文件';        
        return;                            
      }     
      
      let basicParams = {
        ...bucketConf,
        Key: file.name
      };
      let interval = null;
      let getResult = (jobId) => {
        // 查询海报合成任务状态及参数格式，可参考 https://cloud.tencent.com/document/product/460/82391
        cos.request({
          ...basicParams,
          Method: 'GET',
          Url: 'https://' + host + `/pic_jobs/${jobId}`,
          Key: `/pic_jobs/${jobId}`          
        }, (err, data) => {
          if(err) {
            errMsgEle.innerHTML = 'poster检测失败，请在console查看报错信息';
            console.log(JSON.stringify(err));
            return;
          }
          if (data.Response.JobsDetail.State === 'Success') {
            document.getElementById('targetFile').setAttribute('src', 'https://' + bucketConf.Bucket + '.cos.' + bucketConf.Region + '.myqcloud.com/******/***.jpg');
            clearInterval(interval)
          }
        })
      }
      // 商品抠图上传时处理请求及参数格式，可参考 https://cloud.tencent.com/document/product/460/79735
      cos.putObject({
          ...basicParams,
          Body: file,
          Headers: {
            'Pic-Operations': JSON.stringify({
              "is_pic_info": 1,
              "rules": [{
                  "fileid": "***.png",
                  "rule": "ci-process=GoodsMatting"
              }]
            }),
          },
          onProgress: progressData => console.log('上传中，' + JSON.stringify(progressData))
      }, (err, data) => {  
        if(err) {
          errMsgEle.innerHTML = '上传对象失败，请在console查看报错信息';
          console.log(JSON.stringify(err));
          return;
        }        

        sourceFileEle.setAttribute('src', 'https://'+data.Location);
        posterResultsEle.innerHTML = '<li>分析中...</li>';
        // 创建海报合成任务请求及参数格式，可参考 https://cloud.tencent.com/document/product/460/82394
        let host = bucketConf.Bucket + '.ci.' + bucketConf.Region + '.myqcloud.com';
        let body = COS.util.json2xml({
          "Request": {
            "Tag": "PosterProduction",
            "Operation": {
              "Output": {
                "Region": '**-*****',
                "Bucket": '***-125********',
                "Object": "******/***.jpg"
              },
              "PosterProduction": {
                "TemplateId": '635f878c365094e84fc1f499',/** 可指定自定义模板，参考文档 https://cloud.tencent.com/document/product/460/82389，模板文件格式可参考 https://cloud.tencent.com/document/product/460/82397*/
                "Info": {
                  "main": 'https://' + data.Location,
                  "text_te": "***"
                }
              },
              "UserData": "This is my data.",
              "JobLevel": "0"
            },
            "QueueId": "p********************************",
            "CallBack": "",
            "CallBackFormat": "JSON"
          }
        });
        cos.request({
          ...basicParams,
          Method: 'POST',
          Url: 'https://' + host + '/pic_jobs',
          Key: '/pic_jobs', /** 固定值，必须 */
          ContentType: 'application/xml', /** 固定值，必须 */
          Body: body            
        }, (err, data) => {
          
          if(err) {
            errMsgEle.innerHTML = 'poster检测失败，请在console查看报错信息';
            console.log(JSON.stringify(err));
            return;
          }

          let resp = data.Response || {};
          let results = resp.posterInfos || [];

          if (data.Response.JobsDetail.State === 'Submitted') {
            interval = setInterval(() => {
              getResult(data.Response.JobsDetail.JobId)
            }, 3000)
          }
          posterResultsEle.innerHTML = '海报模板已生成'
        })

      });

    }
  </script>
</body>
</html>
